<template>
  <div class="my-posts">
    <div class="page-header">
      <h2>我的帖子</h2>
      <router-link to="/create-post" class="create-btn">
        <a-button type="primary">
          <template #icon><plus-outlined /></template>
          发布新帖子
        </a-button>
      </router-link>
    </div>

    <a-tabs v-model:activeKey="activeTab">
      <a-tab-pane key="all" tab="全部帖子">
        <div class="post-list">
          <a-list :data-source="allPosts" :loading="loading">
            <template #renderItem="{ item }">
              <a-list-item>
                <a-list-item-meta>
                  <template #avatar>
                    <a-avatar :size="64" class="post-avatar">
                      <template v-if="userStore.userInfo?.picture">
                        <img :src="userStore.userInfo.picture" alt="avatar" />
                      </template>
                      <template v-else>
                        <user-outlined />
                      </template>
                    </a-avatar>
                  </template>
                  <template #title>
                    <router-link :to="'/post/' + item.id">
                      <span class="post-title">{{ item.title }}</span>
                    </router-link>
                  </template>
                  <template #description>
                    <div class="post-meta">
                      <div class="meta-top">
                        <span class="time">
                          <clock-circle-outlined /> {{ formatTime(item.createTime || item.createdAt) }}
                        </span>
                        <span class="status" :class="getStatusClass(item.status)">
                          {{ getStatusText(item.status) }}
                        </span>
                        <span v-if="item.categoryName" class="category">
                          <folder-outlined /> {{ item.categoryName }}
                        </span>
                      </div>
                      <div class="meta-stats">
                        <span class="views">
                          <eye-outlined /> {{ item.views || 0 }} 阅读
                        </span>
                        <span class="likes">
                          <like-outlined /> {{ item.likes || 0 }} 点赞
                        </span>
                        <span class="comments">
                          <message-outlined /> {{ item.comments || 0 }} 评论
                        </span>
                      </div>
                      <div v-if="item.summary" class="summary">
                        {{ truncate(item.summary, 100) }}
                      </div>
                    </div>
                  </template>
                </a-list-item-meta>
                <div class="post-actions">
                  <a-button type="link" @click="editPost(item)">
                    <template #icon><edit-outlined /></template>
                    编辑
                  </a-button>
                  <a-popconfirm
                    title="确定要删除这篇帖子吗？"
                    ok-text="确定"
                    cancel-text="取消"
                    @confirm="deletePost(item.id)"
                  >
                    <a-button type="link" danger>
                      <template #icon><delete-outlined /></template>
                      删除
                    </a-button>
                  </a-popconfirm>
                </div>
              </a-list-item>
            </template>
            <template #empty>
              <a-empty description="暂无帖子" />
            </template>
          </a-list>
        </div>
      </a-tab-pane>
      <a-tab-pane key="published" tab="已发布">
        <div class="post-list">
          <a-list :data-source="publishedPosts" :loading="loading">
            <template #renderItem="{ item }">
              <a-list-item>
                <a-list-item-meta>
                  <template #avatar>
                    <a-avatar :size="64" class="post-avatar">
                      <template v-if="userStore.userInfo?.picture">
                        <img :src="userStore.userInfo.picture" alt="avatar" />
                      </template>
                      <template v-else>
                        <user-outlined />
                      </template>
                    </a-avatar>
                  </template>
                  <template #title>
                    <router-link :to="'/post/' + item.id">
                      <span class="post-title">{{ item.title }}</span>
                    </router-link>
                  </template>
                  <template #description>
                    <div class="post-meta">
                      <div class="meta-top">
                        <span class="time">
                          <clock-circle-outlined /> {{ formatTime(item.createTime || item.createdAt) }}
                        </span>
                        <span class="status" :class="getStatusClass(item.status)">
                          {{ getStatusText(item.status) }}
                        </span>
                        <span v-if="item.categoryName" class="category">
                          <folder-outlined /> {{ item.categoryName }}
                        </span>
                      </div>
                      <div class="meta-stats">
                        <span class="views">
                          <eye-outlined /> {{ item.views || 0 }} 阅读
                        </span>
                        <span class="likes">
                          <like-outlined /> {{ item.likes || 0 }} 点赞
                        </span>
                        <span class="comments">
                          <message-outlined /> {{ item.comments || 0 }} 评论
                        </span>
                      </div>
                      <div v-if="item.summary" class="summary">
                        {{ truncate(item.summary, 100) }}
                      </div>
                    </div>
                  </template>
                </a-list-item-meta>
                <div class="post-actions">
                  <a-button type="link" @click="editPost(item)">
                    <template #icon><edit-outlined /></template>
                    编辑
                  </a-button>
                  <a-popconfirm
                    title="确定要删除这篇帖子吗？"
                    ok-text="确定"
                    cancel-text="取消"
                    @confirm="deletePost(item.id)"
                  >
                    <a-button type="link" danger>
                      <template #icon><delete-outlined /></template>
                      删除
                    </a-button>
                  </a-popconfirm>
                </div>
              </a-list-item>
            </template>
            <template #empty>
              <a-empty description="暂无已发布帖子" />
            </template>
          </a-list>
        </div>
      </a-tab-pane>
      <a-tab-pane key="draft" tab="草稿箱">
        <div class="post-list">
          <a-list :data-source="draftPosts" :loading="loading">
            <template #renderItem="{ item }">
              <a-list-item>
                <a-list-item-meta>
                  <template #avatar>
                    <a-avatar :size="64" class="post-avatar">
                      <template v-if="userStore.userInfo?.picture">
                        <img :src="userStore.userInfo.picture" alt="avatar" />
                      </template>
                      <template v-else>
                        <user-outlined />
                      </template>
                    </a-avatar>
                  </template>
                  <template #title>
                    <router-link :to="'/post/' + item.id">
                      <span class="post-title">{{ item.title }}</span>
                    </router-link>
                  </template>
                  <template #description>
                    <div class="post-meta">
                      <div class="meta-top">
                        <span class="time">
                          <clock-circle-outlined /> {{ formatTime(item.createTime || item.createdAt) }}
                        </span>
                        <span class="status" :class="getStatusClass(item.status)">
                          {{ getStatusText(item.status) }}
                        </span>
                        <span v-if="item.categoryName" class="category">
                          <folder-outlined /> {{ item.categoryName }}
                        </span>
                      </div>
                      <div class="meta-stats">
                        <span class="views">
                          <eye-outlined /> {{ item.views || 0 }} 阅读
                        </span>
                        <span class="likes">
                          <like-outlined /> {{ item.likes || 0 }} 点赞
                        </span>
                        <span class="comments">
                          <message-outlined /> {{ item.comments || 0 }} 评论
                        </span>
                      </div>
                      <div v-if="item.summary" class="summary">
                        {{ truncate(item.summary, 100) }}
                      </div>
                    </div>
                  </template>
                </a-list-item-meta>
                <div class="post-actions">
                  <a-button type="link" @click="editPost(item)">
                    <template #icon><edit-outlined /></template>
                    编辑
                  </a-button>
                  <a-popconfirm
                    title="确定要删除这篇帖子吗？"
                    ok-text="确定"
                    cancel-text="取消"
                    @confirm="deletePost(item.id)"
                  >
                    <a-button type="link" danger>
                      <template #icon><delete-outlined /></template>
                      删除
                    </a-button>
                  </a-popconfirm>
                </div>
              </a-list-item>
            </template>
            <template #empty>
              <a-empty description="暂无草稿" />
            </template>
          </a-list>
        </div>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  UserOutlined,
  ClockCircleOutlined,
  EyeOutlined,
  LikeOutlined,
  MessageOutlined,
  FolderOutlined
} from '@ant-design/icons-vue';
import { useUserStore } from '@/stores/user';
import { usePostStore } from '@/stores/post';
import { getUserPosts, deletePost as apiDeletePost } from '@/api/post';
import type { Post } from '@/api/post';

const router = useRouter();
const userStore = useUserStore();
const postStore = usePostStore();

// 状态
const loading = ref(false);
const posts = ref<Post[]>([]);
const activeTab = ref('all');

// 计算属性，根据status过滤出不同状态的帖子
const allPosts = computed(() => posts.value);
const publishedPosts = computed(() => posts.value.filter(post => {
  const status = typeof post.status === 'string' ? parseInt(post.status) : post.status;
  return status === 1;
}));
const draftPosts = computed(() => posts.value.filter(post => {
  const status = typeof post.status === 'string' ? parseInt(post.status) : post.status;
  return status === 0;
}));

// 格式化时间
const formatTime = (time?: string) => {
  if (!time) return '未知时间';
  
  try {
    const date = new Date(time);
    // 检查日期是否有效
    if (isNaN(date.getTime())) {
      return time;
    }
    
    const now = new Date();
    const diff = now.getTime() - date.getTime();
    const oneDay = 24 * 60 * 60 * 1000;
    const oneWeek = 7 * oneDay;
    
    // 如果时间在一天内
    if (diff < oneDay) {
      const hours = Math.floor(diff / (60 * 60 * 1000));
      if (hours < 1) {
        const minutes = Math.floor(diff / (60 * 1000));
        if (minutes < 1) {
          return '刚刚';
        }
        return `${minutes}分钟前`;
      }
      return `${hours}小时前`;
    }
    
    // 如果时间在一周内
    if (diff < oneWeek) {
      const days = Math.floor(diff / oneDay);
      return `${days}天前`;
    }
    
    // 否则显示完整日期
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
  } catch (error) {
    return time;
  }
};

// 获取状态显示文本
const getStatusText = (status: any) => {
  const numStatus = typeof status === 'string' ? parseInt(status) : status;
  if (numStatus === 1) return '已发布';
  if (numStatus === 0) return '草稿';
  if (numStatus === 2) return '待审核';
  if (numStatus === 3) return '已拒绝';
  if (numStatus === 4) return '已删除';
  return '未知状态';
};

// 获取状态样式类
const getStatusClass = (status: any) => {
  const numStatus = typeof status === 'string' ? parseInt(status) : status;
  if (numStatus === 1) return 'published';
  if (numStatus === 0) return 'draft';
  if (numStatus === 2) return 'pending';
  if (numStatus === 3) return 'rejected';
  if (numStatus === 4) return 'deleted';
  return '';
};

// 文本截断函数
const truncate = (text: string, length: number) => {
  if (!text) return '';
  return text.length > length ? text.slice(0, length) + '...' : text;
};

// 获取用户帖子列表
const fetchUserPosts = async () => {
  if (!userStore.isLoggedIn || !userStore.userInfo?.id) {
    message.error('请先登录');
    router.push('/login');
    return;
  }

  try {
    loading.value = true;
    const userId = userStore.userInfo.id;
    console.log(`[我的帖子] 正在获取用户(ID: ${userId})的帖子列表`);
    
    const response = await getUserPosts(userId, { pageSize: 100 });
    console.log('[我的帖子] API响应:', response);
    
    // 处理API响应 - 使用类型断言处理
    const apiResponse = response as any;
    if (apiResponse && apiResponse.code === 200 && Array.isArray(apiResponse.data)) {
      posts.value = apiResponse.data;
      console.log(`[我的帖子] 成功获取到${posts.value.length}篇帖子`);
    } else {
      console.error('[我的帖子] 获取帖子列表失败: 响应格式错误', response);
      message.error('获取帖子列表失败');
    }
  } catch (error) {
    console.error('[我的帖子] 获取帖子列表异常:', error);
    message.error('获取帖子列表失败');
  } finally {
    loading.value = false;
  }
};

// 删除帖子
const deletePost = async (id: number) => {
  try {
    loading.value = true;
    console.log(`[我的帖子] 正在删除帖子(ID: ${id})`);
    
    const response = await apiDeletePost(id);
    console.log('[我的帖子] 删除响应:', response);
    
    // 处理API响应 - 使用类型断言处理
    const apiResponse = response as any;
    if (apiResponse && apiResponse.code === 200) {
      message.success('删除成功');
      posts.value = posts.value.filter(post => post.id !== id);
    } else {
      message.error('删除失败');
    }
  } catch (error) {
    console.error('[我的帖子] 删除帖子异常:', error);
    message.error('删除失败');
  } finally {
    loading.value = false;
  }
};

// 编辑帖子
const editPost = (post: Post) => {
  router.push(`/edit-post/${post.id}`);
};

// 生命周期钩子
onMounted(() => {
  console.log('[我的帖子] 组件挂载');
  fetchUserPosts();
});
</script>

<style lang="scss" scoped>
.my-posts {
  padding: 24px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

    h2 {
      margin: 0;
      font-size: 20px;
      color: rgba(0, 0, 0, 0.85);
    }
  }

  .post-list {
    background: #fff;
    border-radius: 8px;
    padding: 16px;

    :deep(.ant-list-item) {
      padding: 16px;
      transition: background-color 0.3s;

      &:hover {
        background-color: #f8f9fa;
      }
    }

    :deep(.ant-list-item-meta) {
      align-items: flex-start;
      margin-bottom: 8px;

      .ant-avatar {
        background-color: #1890ff;
        border: 2px solid #f0f2f5;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }

      .ant-list-item-meta-title {
        margin-bottom: 8px;
        
        .post-title {
          font-size: 16px;
          font-weight: 600;
          color: #262626;
          
          &:hover {
            color: #1890ff;
            text-decoration: underline;
          }
        }
      }
    }

    .post-meta {
      display: flex;
      flex-direction: column;
      gap: 8px;
      color: rgba(0, 0, 0, 0.45);
      font-size: 13px;

      .meta-top, .meta-stats {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        gap: 16px;
      }

      .time, .category, .views, .likes, .comments {
        display: flex;
        align-items: center;
        gap: 5px;
      }

      .status {
        padding: 2px 8px;
        border-radius: 10px;
        font-size: 12px;

        &.published {
          background: #f6ffed;
          color: #52c41a;
        }

        &.draft {
          background: #f5f5f5;
          color: #8c8c8c;
        }
        
        &.pending {
          background: #e6f7ff;
          color: #1890ff;
        }
        
        &.rejected {
          background: #fff2e8;
          color: #fa8c16;
        }
        
        &.deleted {
          background: #fff1f0;
          color: #f5222d;
        }
      }
      
      .summary {
        margin-top: 8px;
        color: rgba(0, 0, 0, 0.65);
        font-size: 13px;
        line-height: 1.5;
      }
    }

    .post-actions {
      display: flex;
      gap: 8px;
      align-self: flex-start;
      margin-top: 16px;
    }
  }
}
</style> 